<template>
  <div class="app-container">
    <FormItem label="标题" name="username">
      <Input v-model:value="formState.title" allow-clear placeholder="标题" />
    </FormItem>
    <div style="border: 1px solid #ccc; margin-top: 10px">
      <!-- 工具栏 -->
      <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" />
      <!-- 编辑器 -->
      <Editor
        @on-created="handleCreated"
        style="height: 400px; overflow-y: hidden"
        v-model="formState.content"
      />
    </div>

    <a-button class="btn" type="primary" :loading="btnLoading" @click="submit">提交</a-button>
  </div>
</template>

<script lang="ts" setup>
  import { ref, shallowRef } from 'vue'
  import { FormItem, Input, message } from 'ant-design-vue'
  // import type { Rule } from 'ant-design-vue/es/form'
  import { add } from '/@/api/blog'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  import '@wangeditor/editor/dist/css/style.css'

  const emit = defineEmits(['onSuccess'])

  const formState = ref({
    title: '',
    content: '',
  })

  const editorRef = shallowRef()
  const handleCreated = (editor) => {
    editorRef.value = editor
  }

  const btnLoading = ref(false)
  const submit = () => {
    if (!formState.value.title) {
      message.error('请输入标题')
      return false
    }
    if (!formState.value.content) {
      message.error('请输入内容')
      return false
    }

    add(formState.value)
      .then(() => {
        btnLoading.value = false
        emit('onSuccess')
      })
      .catch(() => (btnLoading.value = false))
  }
</script>

<style>
  .center {
    text-align: center;
  }
  .btn {
    margin-top: 20px;
  }
</style>
